<?php

class Basket {

    public function Headers() {
        // returns all arrays for basket
        $array = array(
            "CONTRACT" => array(
                "OfferID" => "OfferID",
                "OfferCost" => "OfferCost",
                "HandsetStockCode" => "HandsetStockCode",
                "HandsetCategory" => "HandsetCategory",
                "HandsetMake" => "HandsetMake",
                "HandsetModel" => "HandsetModel",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "HandsetRefurbished",
                "HandsetThreeGFlag" => "HandsetThreeGFlag",
                "HandsetDescription" => "HandsetDescription",
                "HandsetInsurance" => "HandsetInsurance",
                "TariffNetwork" => "TariffNetwork",
                "TariffServiceProvider" => "TariffServiceProvider",
                "TariffConnectionType" => "TariffConnectionType",
                "TariffContractLength" => "TariffContractLength",
                "TariffName" => "TariffName",
                "TariffCode" => "TariffCode",
                "TariffMinutes" => "TariffMinutes",
                "TariffTexts" => "TariffTexts",
                "TariffLineRental" => "TariffLineRental",
                "TariffSprintCode" => "TariffSprintCode",
                "TariffDescription" => "TariffDescription",
                "VASCode" => "VASCode",
                "VASMRC" => "VASMRC",
                "VASDescription" => "VASDescription",
                "AdditionalCode" => "AdditionalCode",
                "AdditionalMRC" => "AdditionalMRC",
                "AdditionalDescription" => "AdditionalDescription",
                "PromotionalStockCodes" => "PromotionalStockCodes",
                "PromotionalDescriptions" => "PromotionalDescriptions",
                "CashbackStockCodes" => "CashbackStockCodes",
                "CashbackDescriptions" => "CashbackDescriptions",
                "ExpectedGP" => "GP"
            ),
            "DEALBUILDER" => array(
                "HandsetStockCode" => "HandsetStockCode",
                "HandsetCategory" => "SubCategory",
                "HandsetMake" => "Make",
                "HandsetModel" => "Model",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "Refurbished",
                "HandsetThreeGFlag" => "ThreeGFlag",
                "HandsetDescription" => "HandsetDescription",
                "TariffNetwork" => "NetworkProvider",
                "TariffServiceProvider" => "ServiceProvider",
                "TariffConnectionType" => "ConnectionType",
                "TariffContractLength" => "ContractLength",
                "TariffName" => "TariffName",
                "TariffCode" => "TariffCode",
                "TariffMinutes" => "IncMins",
                "TariffTexts" => "IncText",
                "TariffLineRental" => "LineRental",
                "TariffSprintCode" => "SprintCode",
                "TariffDescription" => "TariffDescription",
                "PromotionalStockCodes" => "PromotionalStockCodes",
                "PromotionalDescriptions" => "PromotionalDescriptions"
            ),
            "PAYG" => array(
                "OfferID" => "OfferID",
                "OfferCost" => "OfferCost",
                "HandsetStockCode" => "HandsetStockCode",
                "HandsetCategory" => "HandsetCategory",
                "HandsetMake" => "HandsetMake",
                "HandsetModel" => "HandsetModel",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "HandsetRefurbished",
                "HandsetThreeGFlag" => "HandsetThreeGFlag",
                "HandsetDescription" => "HandsetDescription",
                "HandsetAirtime" => "HandsetAirtime",
                "HandsetAirtimeFL" => "HandsetAirtimeFL",
                "TariffNetwork" => "TariffNetwork",
                "TariffServiceProvider" => "TariffServiceProvider",
                "TariffConnectionType" => "TariffConnectionType",
                "TariffContractLength" => "TariffContractLength",
                "TariffName" => "TariffName",
                "TariffCode" => "TariffCode",
                "TariffMinutes" => "TariffMinutes",
                "TariffTexts" => "TariffTexts",
                "TariffLineRental" => "TariffLineRental",
                "TariffSprintCode" => "TariffSprintCode",
                "TariffDescription" => "TariffDescription",
                "PromotionalStockCodes" => "PromotionalStockCodes",
                "PromotionalDescriptions" => "PromotionalDescriptions",
                "CashbackStockCodes" => "CashbackStockCodes",
                "CashbackDescriptions" => "CashbackDescriptions"
            ),
            "PAYGSIMONLY" => array(
                "OfferID" => "OfferID",
                "OfferCost" => "OfferCost",
                "HandsetStockCode" => "HandsetStockCode",
                "HandsetCategory" => "HandsetCategory",
                "HandsetMake" => "HandsetMake",
                "HandsetModel" => "HandsetModel",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "HandsetRefurbished",
                "HandsetThreeGFlag" => "HandsetThreeGFlag",
                "HandsetDescription" => "HandsetDescription",
                "HandsetAirtime" => "HandsetAirtime",
                "HandsetAirtimeFL" => "HandsetAirtimeFL",
                "TariffNetwork" => "TariffNetwork",
                "TariffServiceProvider" => "TariffServiceProvider",
                "TariffConnectionType" => "TariffConnectionType",
                "TariffContractLength" => "TariffContractLength",
                "TariffName" => "TariffName",
                "TariffCode" => "TariffCode",
                "TariffMinutes" => "TariffMinutes",
                "TariffTexts" => "TariffTexts",
                "TariffLineRental" => "TariffLineRental",
                "TariffSprintCode" => "TariffSprintCode",
                "TariffDescription" => "TariffDescription",
                "PromotionalStockCodes" => "PromotionalStockCodes",
                "PromotionalDescriptions" => "PromotionalDescriptions",
                "CashbackStockCodes" => "CashbackStockCodes",
                "CashbackDescriptions" => "CashbackDescriptions",
                "AccessoryDescription" => "HandsetDescription"
            ),
            "MOBILEBROADBAND" => array(
                "OfferID" => "OfferID",
                "OfferCost" => "OfferCost",
                "HandsetStockCode" => "HandsetStockCode",
                "HandsetCategory" => "HandsetCategory",
                "HandsetMake" => "HandsetMake",
                "HandsetModel" => "HandsetModel",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "HandsetRefurbished",
                "HandsetThreeGFlag" => "HandsetThreeGFlag",
                "HandsetDescription" => "HandsetDescription",
                "HandsetAirtime" => "HandsetAirtime",
                "TariffNetwork" => "TariffNetwork",
                "TariffServiceProvider" => "TariffServiceProvider",
                "TariffConnectionType" => "TariffConnectionType",
                "TariffContractLength" => "TariffContractLength",
                "TariffName" => "TariffName",
                "TariffCode" => "TariffCode",
                "TariffMinutes" => "TariffMinutes",
                "TariffTexts" => "TariffTexts",
                "TariffLineRental" => "TariffLineRental",
                "TariffSprintCode" => "TariffSprintCode",
                "TariffDescription" => "TariffDescription",
                "PromotionalStockCodes" => "PromotionalStockCodes",
                "PromotionalDescriptions" => "PromotionalDescriptions",
                "CashbackStockCodes" => "CashbackStockCodes",
                "CashbackDescriptions" => "CashbackDescriptions",
                "ExpectedGP" => "GP"
            ),
            "SIMFREE" => array(
                "HandsetStockCode" => "StockCode",
                "HandsetMake" => "Make",
                "HandsetModel" => "Model",
                "HandsetColour" => "HandsetColour",
                "HandsetEdition" => "HandsetEdition",
                "HandsetRefurbished" => "Refurbished",
                "HandsetDescription" => "WebDesc",
                "OfferCost" => "Price"
            ),
            "ACCESSORY" => array(
                "AccessoryStockCode" => "StockCode",
                "AccessoryTitle" => "WebDesc",
                "AccessoryDescription" => "ExtendedDesc",
                "AccessoryRRP" => "WebRPHIGH",
                "AccessorySaving" => "WebRPMED",
                "AccessoryPrice" => "WebRPLOW"
            )
        );

        return $array;
    }

    public function GetAction($value) {
        // get action then return true if further reaction is needed
        // empty
        if (array_key_exists('empty', $value)) {
            $sql = Basket::EmptySQL();
            $query = DB::query($sql);
            $_SESSION['GreenMessage'] = Basket::ErrorMessages("3002", '', '');
            return false;
        }
        // edit -- primarily works on the plus or minus quantity buttons
        if (array_key_exists('edit', $value)) {
            $sql = Basket::UpdateSQL($value['ctid'], $value['edit']);
            $query = DB::query($sql);
            return false;
        }
        // edit -- created so quantity can just be set directly
        if (array_key_exists('quantity', $value)) {
            $sql = Basket::UpdateSQL($value['ctid'], "set", $value['quantity']);
            $query = DB::query($sql);
            return false;
        }
        // remove
        if (array_key_exists('remove', $value)) {
            $sql = Basket::RemoveSQL($value['ctid']);
            $query = DB::query($sql);
            return false;
        }
        // checkout
        // REICH - 02.08.2010 - Deactivate standard Checkout
        //if(array_key_exists('checkout', $value)) {
        //	$basket	= Basket::Checkout();
        //		return false;
        //}
        // insurance
        if (array_key_exists('insurance', $value)) {
            $sql = Basket::InsuranceSQL($value['ctid'], $value['yn']);
            $query = DB::query($sql);
            return false;
        }
        // contract
        if (array_key_exists('cdid', $value)) {
            $_SESSION['SQL'] = Basket::ContractSQL($value['cdid']);
            $_SESSION['Category'] = "CONTRACT";
            $_SESSION['Product'] = $value['cdid'];
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // deal builder
        if (array_key_exists('dbid', $value)) {
            $_SESSION['SQL'] = Basket::DealBuilderSQL($value['handset'], $value['connection'], $value['length'], $value['name'], $value['code'], $value['promotion']);
            $_SESSION['Category'] = "DEALBUILDER";
            $_SESSION['Product'] = "";
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // payg
        if (array_key_exists('pgid', $value)) {
            $_SESSION['SQL'] = Basket::PAYGSQL($value['pgid']);
            $_SESSION['Category'] = "PAYG";
            $_SESSION['Product'] = $value['pgid'];
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // payg sim
        if (array_key_exists('psid', $value)) {
            $_SESSION['SQL'] = Basket::PAYGSIMOnlySQL($value['psid']);
            $_SESSION['Category'] = "PAYGSIMONLY";
            $_SESSION['Product'] = $value['psid'];
            $_SESSION['Association'] = $value['ctid'];
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // mobile broadband
        if (array_key_exists('mbid', $value)) {
            $_SESSION['SQL'] = Basket::MobileBroadbandSQL($value['mbid']);
            $_SESSION['Category'] = "MOBILEBROADBAND";
            $_SESSION['Product'] = $value['mbid'];
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // sim free
        if (array_key_exists('sfid', $value)) {
            $_SESSION['SQL'] = Basket::SIMFreeSQL($value['sfid']);
            $_SESSION['Category'] = "SIMFREE";
            $_SESSION['Product'] = $value['sfid'];
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // accessory
        if (array_key_exists('acid', $value)) {
            $_SESSION['SQL'] = Basket::AccessorySQL($value['acid']);
            $_SESSION['Category'] = "ACCESSORY";
            $_SESSION['Product'] = $value['acid'];
            $_SESSION['Association'] = "";
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
        // associated stock
        if (array_key_exists('asid', $value)) {
            $_SESSION['SQL'] = Basket::AccessorySQL($value['asid']);
            $_SESSION['Category'] = "ACCESSORY";
            $_SESSION['Product'] = $value['asid'];
            $_SESSION['Association'] = $value['ctid'];
            // get quantity, default to 1 if not set
            if (!$value['quantity']) {
                $_SESSION['Quantity'] = 1;
            } else {
                $_SESSION['Quantity'] = $value['quantity'];
            }
            return true;
        }
    }

    public function Process() {
        // basket limits
        // there was an action required, now do it
        $headers = Basket::Headers();
        $columns = "ShopCode, SessionID, Category, Quantity, Affiliate, Association, ";
        $data = "'" . $_SESSION['ShopCode'] . "', " .
                "'" . $_SESSION['esid'] . "', " .
                "'" . $_SESSION['Category'] . "', " .
                "'" . $_SESSION['Quantity'] . "', " .
                "'" . $_SESSION['Affiliate'] . "', " .
                "'" . $_SESSION['Association'] . "', ";
        $count = 0;
        $comma = "";
        // check product exists
        $query = DB::query($_SESSION['SQL']);
        // if it doesn't exist, return error to basket, else carry on
        if (DB::count($query) < 1) {
            // the item does not exist... tell the user
            $_SESSION['RedMessage'] = Basket::ErrorMessages("1001", '', '');
        } else {
            // item exists
            $result = DB::fetch($query);
            // get key that is needed, then loop through remaining data
            foreach ($headers as $keys => $values) {
                if ($keys == $_SESSION['Category']) {
                    foreach ($values as $key => $value) {
                        // get network for session variable
                        if ($key == "TariffNetwork") {
                            $_SESSION['Network'] = $result[$value];
                        }
                        // continue building string
                        if ($count >= 1) {
                            $comma = ", ";
                        }
                        // columns
                        $columns .= $comma . $key;
                        // insert data
                        $data .= $comma . "'" . addslashes($result[$value]) . "'";
                        $count++;
                    }
                }
            }
            // build into sql
            $insert = Basket::AddSQL($columns, $data);
            $check = Basket::CheckSQL($_SESSION['Category'], $_SESSION['Product'], $_SESSION['Association']);
            $quantity = DB::count(DB::query($check));
            // if the item is already in basket, increment value and check against maximum
            if ($quantity > 0) {
                // update quantity
                $cart_result = DB::fetch(DB::query($check));
                $update = Basket::UpdateSQL($cart_result['CartID'], "plus", $_SESSION['Quantity']);
                $_SESSION['GreenMessage'] = Basket::ErrorMessages("3001", $cart_result['Description'], '');
                $send = DB::query($update);
            } else {
                // add item
                $add = DB::query($insert);
                $_SESSION['LastInsertID'] = DB::last_insert();
            }
        }
    }

    public function TotalCost() {
        // gets basket total
        $total = 0;
        $sql = Basket::All();
        $query = DB::query($sql);

        // loop through each line
        while ($result = DB::fetch($query)) {
            $handsets = ($result['OfferCost'] + $result['HandsetAirtime']) * $result['Quantity'];
            $accessories = ($result['AccessoryPrice'] * $result['Quantity']);
            $total += ( $handsets + $accessories);
        }

        // set it to correct number format
        $total = number_format($total, 2, ".", ",");

        return $total;
    }

    public function TotalItems() {
        // gets basket quantity
        $quantity = 0;
        $sql = Basket::All();
        $query = DB::query($sql);

        // loop through each line
        while ($result = DB::fetch($query)) {
            $quantity += $result['Quantity'];
        }

        return $quantity;
    }

    public function Summary() {
        // gets basket total
        $result['cost'] = Basket::TotalCost();
        // gets basket quantity
        $result['quantity'] = Basket::TotalItems();

        return $result;
    }

    public function XNetwork($type) {
        // get sql statement
        $sql = Basket::XNetworkSQL($type);
        $query = DB::query($sql);

        // return true if only one, flase if more than one
        if (DB::count($query) > 1) {
            return false;
        } else {
            return true;
        }
    }

    public function UnsetVars() {
        // unset session vars used in basket
        unset($_SESSION['Association']);
        unset($_SESSION['Category']);
        unset($_SESSION['Network']);
        unset($_SESSION['Product']);
        unset($_SESSION['Quantity']);
        unset($_SESSION['SQL']);
        unset($_SESSION['LastInsertID']);
        unset($_SESSION['Message']);
        unset($_SESSION['RedMessage']);
        unset($_SESSION['AmberMessage']);
        unset($_SESSION['GreenMessage']);
        unset($_SESSION['Checkout']);
    }

    public function CheckoutArray() {
        // set basic variables for this process
        $cost = 0;
        $handset_id = 0;
        $accessory_id = 0;
        $associated_id = 0;
        $quantity = 0;
        $expected_gp = 0;

        // affiliate used variables
        // webgains
        if ($_SESSION['ShopCode'] == "AFM") {
            $wg_Items = "";
            $wg_Array = "";
            $wg_ID = 0;
            $wg_ContractID = 2155;
            $wg_Contract = "Contract Phone";
            $wg_PrepayID = 2159;
            $wg_Prepay = "PAYG Phone";
            $wg_LoadedID = 4487;
            $wg_Loaded = "Fully Loaded";
            $wg_PrepaySIMID = 4362;
            $wg_PrepaySIM = "Prepay SIM";
            $wg_SIMFreeID = 2158;
            $wg_SIMFree = "SIM Free";
            $wg_AccessoryID = 2160;
            $wg_Accessory = "Accessory";
        } elseif ($_SESSION['ShopCode'] == "GOM") {
            $wg_Items = "";
            $wg_Array = "";
            $wg_ID = 0;
            $wg_ContractID = 3416;
            $wg_Contract = "Contract Phone";
            $wg_PrepayID = 3726;
            $wg_Prepay = "PAYG Phone";
            $wg_LoadedID = 4489;
            $wg_Loaded = "Fully Loaded";
            $wg_PrepaySIMID = 4412;
            $wg_PrepaySIM = "Prepay SIM";
            $wg_SIMFreeID = 3725;
            $wg_SIMFree = "SIM Free";
            $wg_AccessoryID = 3727;
            $wg_Accessory = "Accessory";
        }
        // affiliate future
        $af_Items = "";
        $af_Array = "";
        $af_ID = 0;
        $af_Separator = "";
        $af_Contract = "Contracts";
        $af_Prepay = "PAYG";
        $af_PrepaySIM = "FreeSim";
        $af_SIMFree = "SimFree";
        $af_Accessory = "Accessory";
        // yahoo
        $ya_ID = "";
        $ya_Unit = "";
        $ya_Price = "";
        // dgm
        $dgm_Items = "";
        $dgm_Array = "";
        $dgm_ID = 0;
        $dgm_Separator = "";
        $dgm_Contract = "Contracts";
        $dgm_Prepay = "PAYG";
        $dgm_PrepaySIM = "FreeSim";
        $dgm_SIMFree = "SimFree";
        $dgm_Accessory = "Accessory";

        // limit variables
        $contract_qty = 0;
        $prepay_qty = 0;
        $prepaysim_qty = 0;
        $simfree_qty = 0;
        $accessory_qty = 0;

        $sql = Basket::All();
        $query = DB::query($sql);

        // create array for new checkout
        while ($result = DB::fetch($query)) {
            if ($result['Category'] == "CONTRACT" || $result['Category'] == "DEALBUILDER" || $result['Category'] == "PAYG" || $result['Category'] == "MOBILEBROADBAND" || $result['Category'] == "PAYGSIMONLY") {
                // then loop through
                while ($quantity != $result['Quantity']) {
                    // set arrays and ids back to blank / 0
                    $associated_array = "";
                    $associated_id = 0;
                    $promotional_array = "";
                    $promotional_id = 0;
                    $bolt_on_array = "";
                    $bolt_on_id = 0;

                    // get category for limits and increment
                    if ($result['Category'] == "CONTRACT" || $result['Category'] == "DEALBUILDER" || $result['Category'] == "MOBILEBROADBAND") {
                        $contract_qty++;
                        $category = "CONTRACT";
                        // webgains
                        $wg_CategoryID = $wg_ContractID;
                        $wg_Category = $wg_Contract;
                        // affiliate future
                        $af_Category = $af_Contract;
                    } elseif ($result['Category'] == "PAYG") {
                        $prepay_qty++;
                        $category = "PAYG";
                        // webgains
                        $wg_CategoryID = $wg_PrepayID;
                        $wg_Category = $wg_Prepay;
                        // affiliate future
                        $af_Category = $af_Prepay;
                    } else {
                        $prepaysim_qty++;
                        $category = "PAYGSIMONLY";
                        // webgains
                        $wg_CategoryID = $wg_PrepaySIMID;
                        $wg_Category = $wg_PrepaySIM;
                        // affiliate future
                        $af_Category = $af_PrepaySIM;
                    }

                    // created associated stock array
                    $as_sql = Basket::Association($result['CartID']);
                    $as_query = DB::query($as_sql);

                    // loop through all associations if there are some
                    if (DB::count($as_query) > 0) {
                        while ($as_result = DB::fetch($as_query)) {
                            // do not include prepay sims
                            if ($as_result['Category'] != "PAYGSIMONLY") {
                                $associated_array[$associated_id] = array(
                                    'stock_code' => $as_result['AccessoryStockCode'],
                                    'price' => $as_result['AccessoryPrice'],
                                    'quantity' => $as_result['Quantity'],
                                    'sim_free' => 'N',
                                    'description' => $as_result['AccessoryDescription'],
                                    'image' => Basket::ImageURL(
                                            $_SESSION['ShopCode'],
                                            "ACCESSORY",
                                            "",
                                            $as_result['AccessoryStockCode']
                                    )
                                );

                                // webgains
                                $wg_Array[$wg_ID] =
                                        $wg_AccessoryID .
                                        "::" .
                                        $as_result['AccessoryPrice'] .
                                        "::" .
                                        $wg_Accessory .
                                        "::" .
                                        $as_result['AccessoryStockCode'];
                                $wg_ID++;

                                // affiliate future
                                $af_Array[$af_Category] += ( $as_result['AccessoryPrice'] * $as_result['Quantity']);

                                // dgm
                                $dgm_Array[$dgm_Accessory][$dgm_ID] =
                                        $as_result['AccessoryPrice'] .
                                        "|" .
                                        $as_result['AccessoryDescription'];
                                $dgm_ID++;

                                // yahoo
                                $ya_Units[$ya_ID] = $as_result['Quantity'];
                                $ya_Prices[$ya_ID] = $as_result['AccessoryPrice'];
                                $ya_ID++;

                                $associated_id++;
                                $cost += ( $as_result['AccessoryPrice'] * $as_result['Quantity']);

                                // increment limit variable
                                $accessory_qty += $as_result['Quantity'];
                            }
                        }
                    }

                    // create blank array if there are no associations
                    if (!is_array($associated_array)) {
                        $associated_array = array();
                    }

                    // create promos array
                    if ($result['PromotionalStockCodes'] != "0" || $result['PromotionalStockCodes'] == "") {
                        $promotional_array[$promotional_id] = array(
                            'stock_code' => $result['PromotionalStockCodes'],
                            'instant' => Basket::PromotionType($result['PromotionalStockCodes']),
                            'description' => $result['PromotionalDescriptions'],
                            'image' => Basket::ImageURL(
                                    $_SESSION['ShopCode'],
                                    "ACCESSORY",
                                    "",
                                    $result['PromotionalStockCodes']
                            )
                        );
                        $promotional_id++;
                    }
                    // cashback
                    if ($result['CashbackStockCodes'] != "0" || $result['CashbackStockCodes'] == "") {
                        $promotional_array[$promotional_id] = array(
                            'stock_code' => $result['CashbackStockCodes'],
                            'instant' => 'N',
                            'description' => $result['CashbackDescriptions'],
                            'image' => Basket::ImageURL(
                                    $_SESSION['ShopCode'],
                                    "ACCESSORY",
                                    "",
                                    $result['CashbackStockCodes']
                            )
                        );
                        $promotional_id++;
                    }

                    // if there are no promo's, it must be an array
                    if (!is_array($promotional_array)) {
                        $promotional_array = array();
                    }

                    // create handset description
                    $handset_description = Basket::HandsetDescription($result, $result['Category']);

                    // create handset array
                    $handset_array[$handset_id] = array(
                        'network' => $result['TariffNetwork'],
                        'service_provider' => $result['TariffServiceProvider'],
                        'tarif_code' => $result['TariffCode'],
                        'connection_type' => $result['TariffConnectionType'],
                        'sprint_code' => $result['TariffSprintCode'],
                        'imei' => '',
                        'stock_code' => $result['HandsetStockCode'],
                        'price' => ($result['OfferCost'] + $result['HandsetAirtime']),
                        'monthly_cost' => $result['TariffLineRental'],
                        'category' => $result['HandsetCategory'],
                        'promos' => $promotional_array,
                        'accessories' => $associated_array,
                        'deal_id' => $result['OfferID'],
                        'type' => $category,
                        'network_technology' => $result['HandsetThreeGFlag'],
                        'description' => $handset_description,
                        'image' => Basket::ImageURL(
                                $_SESSION['ShopCode'],
                                "HANDSET",
                                $result['HandsetMake'],
                                $result['HandsetModel'],
                                $result['HandsetColour'],
                                $result['HandsetEdition']
                        ),
                        // defined specifically for us to use
                        'quantity' => 1
                    );

                    // insurance
                    if ($result['HandsetInsurance'] != "N") {
                        // there is insurance, get insurance type
                        $type = Basket::Insurance($result['HandsetInsurance']);
                        $insurance = array('insurance' => $type);
                        $handset_array[$handset_id] = array_merge($handset_array[$handset_id], $insurance);
                    }

                    // value added services
                    if ($result['VASCode']) {
                        $bolt_on_array[$bolt_on_id] = array(
                            'type' => 'VAS',
                            'code' => $result['VASCode'],
                            'monthly_cost' => $result['VASMRC'],
                            'description' => $result['VASDescription'],
                            'image' => ''
                        );
                        $bolt_on_id++;
                    }

                    // additionals
                    if ($result['AdditionalCode']) {
                        $bolt_on_array[$bolt_on_id] = array(
                            'type' => 'ADDITIONAL',
                            'code' => $result['AdditionalCode'],
                            'monthly_cost' => $result['AdditionalMRC'],
                            'description' => $result['AdditionalDescription'],
                            'image' => ''
                        );
                        $bolt_on_id++;
                    }

                    // add value added services and additionals to array
                    if (is_array($bolt_on_array)) {
                        $bolt_on = array('bolt_ons' => $bolt_on_array);
                        $handset_array[$handset_id] = array_merge($handset_array[$handset_id], $bolt_on);
                    }

                    // expected gp
                    $expected_gp += $result['ExpectedGP'];

                    // fully loaded phone requires seperate tracking
                    if ($result['HandsetAirtimeFL'] > 0 && $result['HandsetAirtimeFL'] != "") {
                        $wg_CategoryID = $wg_LoadedID;
                        $wg_Category = $wg_Loaded;
                    }

                    // webgains
                    $wg_Array[$wg_ID] =
                            $wg_CategoryID .
                            "::" .
                            ($result['OfferCost'] + $result['HandsetAirtime']) .
                            "::" .
                            $wg_Category .
                            "::" .
                            $result['HandsetStockCode'];
                    $wg_ID++;

                    // affiliate future
                    $af_Array[$af_Category] += ( $result['OfferCost'] + $result['HandsetAirtime']);

                    // dgm
                    $dgm_Array[$dgm_Category][$dgm_ID] =
                            ($result['OfferCost'] + $result['HandsetAirtime']) .
                            "|" .
                            $result['HandsetDescription'] .
                            "|" .
                            $result['TariffDescription'];
                    $dgm_ID++;

                    // yahoo
                    $ya_Units[$ya_ID] = 1;
                    $ya_Prices[$ya_ID] = ($result['OfferCost'] + $result['HandsetAirtime']);
                    $ya_ID++;

                    $handset_id++;
                    $quantity++;
                    $cost += ( $result['OfferCost'] + $result['HandsetAirtime']);
                }

                $quantity = 0;
            } elseif ($result['Category'] == "SIMFREE") {
                // increment limit variable
                $simfree_qty = $result['Quantity'];

                // create array
                $accessory_array[$accessory_id] = array(
                    'stock_code' => $result['HandsetStockCode'],
                    'price' => ($result['OfferCost'] * $result['Quantity']),
                    'quantity' => $result['Quantity'],
                    'sim_free' => 'Y',
                    'description' => $result['HandsetDescription'],
                    'image' => Basket::ImageURL(
                            $_SESSION['ShopCode'],
                            $result['Category'],
                            $result['HandsetMake'],
                            $result['HandsetModel'],
                            $result['HandsetColour'],
                            $result['HandsetEdition']
                    )
                );

                // webgains
                $wg_Array[$wg_ID] =
                        $wg_SIMFreeID .
                        "::" .
                        ($result['OfferCost'] * $result['Quantity']) .
                        "::" .
                        $wg_SIMFree .
                        "::" .
                        $result['HandsetStockCode'];
                $wg_ID++;

                // affiliate future
                $af_Array[$af_Category] += ( $result['OfferCost'] * $result['Quantity']);

                // dgm
                $dgm_Array[$dgm_Category][$dgm_ID] =
                        ($result['OfferCost'] * $result['Quantity']) .
                        "|" .
                        $result['HandsetDescription'];
                $dgm_ID++;

                // yahoo
                $ya_Units[$ya_ID] = $result['Quantity'];
                $ya_Prices[$ya_ID] = ($result['OfferCost'] * $result['Quantity']);
                $ya_ID++;

                $accessory_id++;
                $cost += ( $result['OfferCost'] * $result['Quantity']);
            } else {
                // it can now only be an accessory, do not include associated or prepay sims
                if ($result['Association'] == "0" && $category != "PAYGSIMONLY") {
                    // increment limit variable
                    $accessory_qty += $result['Quantity'];

                    // create array
                    $accessory_array[$accessory_id] = array(
                        'stock_code' => $result['AccessoryStockCode'],
                        'price' => $result['AccessoryRRP'],
                        'quantity' => $result['Quantity'],
                        'sim_free' => 'N',
                        'description' => $result['AccessoryTitle'],
                        'image' => Basket::ImageURL(
                                $_SESSION['ShopCode'],
                                $result['Category'],
                                "",
                                $result['AccessoryStockCode'],
                                "",
                                "",
                                ""
                        )
                    );

                    // webgains
                    $wg_Array[$wg_ID] =
                            $wg_AccessoryID .
                            "::" .
                            ($result['AccessoryRRP'] * $result['Quantity']) .
                            "::" .
                            $wg_Accessory .
                            "::" .
                            $result['AccessoryStockCode'];
                    $wg_ID++;

                    // affiliate future
                    $af_Array[$af_Category] += ( $result['AccessoryRRP'] * $result['Quantity']);

                    // dgm
                    $dgm_Array[$dgm_Accessory][$dgm_ID] =
                            ($result['AccessoryRRP'] * $result['Quantity']) .
                            "|" .
                            $result['AccessoryTitle'];
                    $dgm_ID++;

                    // yahoo
                    $ya_Units[$ya_ID] = $result['Quantity'];
                    $ya_Prices[$ya_ID] = ($result['AccessoryPrice'] * $result['Quantity']);
                    $ya_ID++;

                    $accessory_id++;
                    $cost += ( $result['AccessoryRRP'] * $result['Quantity']);
                }
            }
        }

        // now check limits on basket, starting on x network contract
        if (!$_SESSION['ContractXNetwork']) {
            if (!Basket::XNetwork("CONTRACT")) {
                $error[$error_id] = Basket::ErrorMessages("2005", '', '');
                $error_id++;
            }
        }
        // prepay x network
        if (!$_SESSION['PrepayXNetwork']) {
            if (!Basket::XNetwork("PAYG")) {
                $error[$error_id] = Basket::ErrorMessages("2006", '', '');
                $error_id++;
            }
        }
        // contract limits
        if ($contract_qty > $_SESSION['ContractLimit']) {
            $error[$error_id] = Basket::ErrorMessages("2001", '', $_SESSION['ContractLimit']);
            $error_id++;
        }
        // prepay limits
        if ($prepay_qty > $_SESSION['PrepayLimit']) {
            $error[$error_id] = Basket::ErrorMessages("2002", '', $_SESSION['PrepayLimit']);
            $error_id++;
        }
        // prepay sim limits
        if ($prepaysim_qty > $_SESSION['PrepaySIMLimit']) {
            $error[$error_id] = Basket::ErrorMessages("2007", '', $_SESSION['PrepaySIMLimit']);
            $error_id++;
        }
        // sim free limits
        if ($simfree_qty > $_SESSION['SIMFreeLimit']) {
            $error[$error_id] = Basket::ErrorMessages("2003", '', $_SESSION['SIMFreeLimit']);
            $error_id++;
        }
        // accessory limits
        if ($accessory_qty > $_SESSION['AccessoryLimit']) {
            $error[$error_id] = Basket::ErrorMessages("2004", '', $_SESSION['AccessoryLimit']);
            $error_id++;
        }
        // if one has failed, $error should be an array
        if (is_array($error)) {
            // loop through each message adding to list
            $list = "<ul>";
            foreach ($error as $value) {
                $list .= "<li>$value</li>";
            }
            $list .= "</ul>";
            $_SESSION['AmberMessage'] = "You cannot proceed to the checkout until you have rectified the following:$list";
        }

        // check they are arrays, if they arent just simply create blanks
        if (!is_array($accessory_array)) {
            $accessory_array = array();
        }
        if (!is_array($handset_array)) {
            $handset_array = array();
        }

        // get analytics data
        $analytics_id = 0;
        $analytics_array[$analytics_id] = SiteDefaults::Analytics($_SESSION['ShopCode'], $_SESSION['Environment']);
        $analytics_id++;

        // google conversion code for gomobile sim sales only...
        if (DB::count(DB::query(Basket::All())) == 1 && $_SESSION['Checkout'] && !$_REQUEST['show'] && $_SESSION['ShopCode'] == "GOM") {
            $result = DB::fetch(DB::query(Basket::All()));
            if ($result['Category'] == "PAYGSIMONLY") {
                $analytics_array[$analytics_id] = SiteDefaults::Conversion($_SESSION['ShopCode'], $_SESSION['Environment']);
            }
        }

        // explode affiliate strings
        // webgains
        if ($wg_Array)
            $wg_Items = implode("|", $wg_Array);
        // affiliate future
        if ($af_Array)
            foreach ($af_Array as $key => $value) {
                if ($af_ID > 0) {
                    $af_Separator = ",";
                }
                $af_Items .= $af_Separator . $key . "," . $value;
                $af_ID++;
            }
        // yahoo
        if ($ya_Units)
            $ya_Units = implode(";", $ya_Units);
        if ($ya_Prices)
            $ya_Prices = implode(";", $ya_Prices);

        // get affiliate data
        $affiliate_array = "";
        $affiliate_id = 0;

        // only post affiliate data if its not jemm
        if (strtolower($_SESSION['Affiliate']) != "jemm") {
            $affiliate_array[$affiliate_id] = SiteDefaults::AffiliateTracking(strtolower($_SESSION['Affiliate']), $_SESSION['ShopCode'], $cost, $wg_Items, $af_Items, $dgm_Array, $ya_Units, $ya_Prices, $_SESSION['VoucherCode']);
            $affiliate_id++;
        } else {
            // its a jemm sale, so only post on sim sales for gomobile
            if (DB::count(DB::query(Basket::All())) == 1 && $_SESSION['Checkout'] && !$_REQUEST['show'] && $_SESSION['ShopCode'] == "GOM") {
                $result = DB::fetch(DB::query(Basket::All()));
                if ($result['Category'] == "PAYGSIMONLY") {
                    $affiliate_array[$affiliate_id] = SiteDefaults::AffiliateTracking(strtolower($_SESSION['Affiliate']), $_SESSION['ShopCode'], $cost, $wg_Items, $af_Items, $dgm_Array, $ya_Units, $ya_Prices, $_SESSION['VoucherCode']);
                    $affiliate_id++;
                }
            }
        }

        // tesco only
        if ($_SESSION['ShopCode'] == "TES") {
            $affiliate_array[$affiliate_id] = SiteDefaults::AffiliateTracking(strtolower("yahoo"), $_SESSION['ShopCode'], $cost, $wg_Items, $af_Items, $dgm_Array, $ya_Units, $ya_Prices, $_SESSION['VoucherCode']);
            $affiliate_id++;
        }

        // check its an array
        if (!is_array($analytics_array)) {
            $analytics_array = array();
        }
        if (!is_array($affiliate_array)) {
            $affiliate_array = array();
        }

        // total items of basket
        $total_items = Basket::TotalItems();

        // complete array
        $basketArray = array(
            'total' => $cost,
            'expected_web_gp' => $expected_gp,
            'branch_code' => $_SESSION['BranchCode'],
            'affiliate_code' => strtolower($_SESSION['Affiliate']),
            'includes' => array('analytics' => $analytics_array, 'affiliates' => $affiliate_array),
            'bulk_order' => '1',
            'accessories' => $accessory_array,
            'handsets' => $handset_array
        );

        return $basketArray;
    }

    public function Checkout() {
        // get basket array
        $array = Basket::CheckoutArray();

        // encode basket
        $encoded = Basket::UTF8Encode($array);
        $encoded = json_encode($encoded);
        $encoded = base64_encode($encoded);
        $encoded = urlencode($encoded);

        // get checkout url
        $url = SiteDefaults::CheckoutURL($_SESSION['ShopCode'], $_SESSION['Environment']);

        // post to checkout
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url . 'checkout/start');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'password=tinker&basket=' . $encoded);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $response = curl_exec($ch);
        curl_close($ch);

        // see if there is an error
        $find = "ERROR";
        var_dump($response);
        $result = strpos($response, $find);

        // see if there is an error, otherwise post
        if ($result === false) {
            header('Location: ' . $url . 'checkout/start?basket_id=' . $response);
            exit();
        } else {
            $_SESSION['RedMessage'] = Basket::ErrorMessages("1003", "", "");
        }
    }

    public function HandsetDescription($value, $type) {
        if ($type == "PAYG" || $type == "PAYGSIM") {
            // create user friendly string for basket / checkout
            $handset = $value['HandsetDescription'];
            $tariff = " on " . ucwords(strtolower($value['TariffNetwork']));

            // work out if there is a promotion
            if ($value['HandsetAirtime'] > 0) {
                $airtime = " + �" . $value['HandsetAirtime'] . " Airtime";
            }
            // work out if there is a cashback
            if ($value['HandsetAirtimeFL'] > 0) {
                $loaded = " + �" . $value['HandsetAirtimeFL'] . " Fully Loaded Airtime";
            }

            // put all strings together
            $description = $handset . $tariff . $airtime . $loaded;
        } else {
            // create user friendly string for basket / checkout
            $handset = $value['HandsetDescription'];
            $tariff = " " . $value['TariffNetwork'] .
                    " " . $value['TariffDescription'] .
                    " (" . $value['TariffContractLength'] . " months)";

            // work out if there is a promotion
            if ($value['PromotionalStockCodes'] > 0) {
                $promotion = " + " . $value['PromotionalDescriptions'];
            }
            // work out if there is a cashback
            if ($value['CashbackStockCodes'] > 0) {
                $cashback = " with " . $value['CashbackDescriptions'];
            }

            // put all strings together
            $description = $handset . $tariff . $promotion . $cashback;
        }

        return $description;
    }

    ///////////////////////////////////////////////////
    ///					SQL Queries					///
    ///////////////////////////////////////////////////

    public function AddSQL($columns, $data) {
        // build sql statement
        $sql = new SQL();

        $sql->insert[] = "Basket";
        $sql->insert[] = $columns;
        $sql->values[] = $data;

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function RemoveSQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->delete[] = "Basket";
        $sql->where[] = "CartID = '$id'";
        $sql->or[] = "Association = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function CheckSQL($type, $id, $association=null) {
        // build sql statement
        $sql = new SQL();

        // get column to check value against
        $column = Basket::Categories($type);
        $description = Basket::Descriptions($type);

        $sql->select[] = "B.CartID";
        $sql->select[] = "B.$description AS Description";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.Category = '$type'";
        $sql->where[] = "B.$column = '$id'";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        // could be associated, so add line
        if ($association) {
            $sql->where[] = "B.Association = '$association'";
        } else {
            $sql->where[] = "B.Association = ''";
        }

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function UpdateSQL($id, $method, $quantity) {
        // build sql statement
        $sql = new SQL();

        // convert method to symbol
        if ($method == "plus") {
            $method = "+";
        } else if ($method == "minus") {
            $method = "-";
        } else if ($method == "set") {  //added method so quantity can just be set to a value (add extra checks to incoming data)
            $method = "=";
        } else { //no method set, default to plus
            $method = "+";
        }

        // see if a value for quantity has been supplied, default to 1
        if (!isset($quantity) || !$quantity || !is_numeric($quantity)) {
            $quantity = 1;
        }

        // get column to check value against
        $column = Basket::Categories($type);

        $sql->update[] = "Basket";
        if ($method != "=") {
            $sql->set[] = "Quantity = Quantity" . $method . $quantity;
        } else {
            $sql->set[] = "Quantity = " . $quantity;
        }
        $sql->where[] = "CartID = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function EmptySQL() {
        // build sql statement
        $sql = new SQL();

        $sql->delete[] = "Basket";
        $sql->where[] = "SessionID = '" . $_SESSION['esid'] . "'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function XNetworkSQL($type) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Category = '$type'";
        $sql->group[] = "B.TariffNetwork";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function ContractSQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "C.*";
        $sql->from[] = "DealsContract C";
        $sql->where[] = "C.OfferID = '$id'";
        $sql->where[] = "C.ShopCode = '" . $_SESSION['ShopCode'] . "'";
        $sql->where[] = "C.Archived != 'archived'";
        $sql->where[] = "C.InError != 'error'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function DealBuilderSQL($handset, $connection, $length, $name, $code, $promotion) {
        // build sql statement
        $sql = new SQL();
        $union = new SQL();

        $sql->select[] = "H.*";
        $sql->select[] = "H.WebDesc AS HandsetDescription";
        $sql->select[] = "C.*";
        $sql->select[] = "A.*";
        $sql->select[] = "A.StockCode AS PromotionalStockCodes";
        $sql->select[] = "A.WebDesc AS PromotionalDescriptions";
        $sql->select[] = "T.WebDescription AS TariffDescription";
        $sql->from[] = "HandsetStock H";
        $sql->from[] = "CommissionsTable C";
        $sql->from[] = "AccessoryStock A";
        $sql->from[] = "ContractTariffs T";
        $sql->where[] = "H.StockCode = C.HandsetStockCode";
        $sql->where[] = "T.TariffNo = C.TariffNo";
        $sql->where[] = "C.HandsetStockCode = '$handset'";
        $sql->where[] = "C.ConnectionType = '$connection'";
        $sql->where[] = "C.ContractLength = '$length'";
        $sql->where[] = "C.TariffName = '$name'";
        $sql->where[] = "C.TariffCode = '$code'";
        $sql->where[] = "A.StockCode = '$promotion'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function PAYGSQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "P.*";
        $sql->from[] = "DealsPAYG P";
        $sql->where[] = "P.OfferID = '$id'";
        $sql->where[] = "P.ShopCode = '" . $_SESSION['ShopCode'] . "'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function PAYGSIMOnlySQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "P.*";
        $sql->from[] = "DealsPAYGSIMOnly P";
        $sql->where[] = "P.OfferID = '$id'";
        $sql->where[] = "P.ShopCode = '" . $_SESSION['ShopCode'] . "'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function MobileBroadbandSQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "M.*";
        $sql->from[] = "DealsBroadband M";
        $sql->where[] = "M.OfferID = '$id'";
        $sql->where[] = "M.ShopCode = '" . $_SESSION['ShopCode'] . "'";
        $sql->where[] = "M.Archived != 'archived'";
        $sql->where[] = "M.InError != 'error'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function SIMFreeSQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "S.*";
        $sql->select[] = "S." . $_SESSION['SIMFreePrice'] . " AS Price";
        $sql->from[] = "SIMFreeStock S";
        $sql->where[] = "S.StockCode = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function AccessorySQL($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "A.*";
        $sql->select[] = "A." . $_SESSION['AccessoryPrice'] . " AS Price";
//		$sql->from[]		= "AccessoryStock A";
        $sql->from[] = "CostBiterStock A";
        $sql->where[] = "A.StockCode = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function AssociatedStockSQL($make, $model, $category) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "R.*";
        $sql->select[] = "A.*";
        $sql->from[] = "AssociatedStock R";
        $sql->inner[] = "AccessoryStock A ON R.StockCode = A.StockCode";
        $sql->where[] = "R.Manufacturer = '$make'";
        $sql->where[] = "R.ModelNumber = '$model'";
        // check category for value
        if ($category) {
            // it has a value, so work out extra statement
            if ($category == "98") {
                $sql->where[] = "R.SellfoneCategory LIKE '%batteries%'";
            } else {
                $sql->where[] = "R.WebCategoryID = '$category'";
                $sql->where[] = "R.SellfoneCategory NOT LIKE '%batteries%'";
            }
        }
        $sql->order[] = "A.WebRPHIGH ASC";
        $sql->limit[] = "0, 30";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function InsuranceSQL($id, $yn) {
        // build sql statement
        $sql = new SQL();

        $sql->update[] = "Basket";
        $sql->set[] = "HandsetInsurance = '$yn'";
        $sql->where[] = "CartID = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    ///////////////////////////////////////////////////
    ///					Basket SQL					///
    ///////////////////////////////////////////////////

    public function SQL() {
        // build sql statement for basket contents
        $sql['contract'] = Basket::Contract();
        $sql['mobilebroadband'] = Basket::MobileBroadband();
        $sql['payg'] = Basket::PAYG();
        $sql['simfree'] = Basket::SIMFree();
        $sql['accessory'] = Basket::Accessory();

        return $sql;
    }

    public function All() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function Contract() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Category = 'CONTRACT'";
        $sql->or[] = "B.Category = 'DEALBUILDER'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function MobileBroadband() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Category = 'MOBILEBROADBAND'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function PAYG() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Category = 'PAYG'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function SIMFree() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Category = 'SIMFREE'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function Accessory() {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "(B.Category = 'ACCESSORY' OR B.Category = 'PAYGSIMONLY')";
        $sql->where[] = "B.Association = '0'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    public function Association($id) {
        // build sql statement
        $sql = new SQL();

        $sql->select[] = "B.*";
        $sql->from[] = "Basket B";
        $sql->where[] = "B.SessionID = '" . $_SESSION['esid'] . "'";
        $sql->where[] = "B.Association = '$id'";

        // send to string
        $sql = $sql->ToString($sql);

        return $sql;
    }

    ///////////////////////////////////////////////////
    ///				Private Functions				///
    ///////////////////////////////////////////////////

    private function PromotionType($stockcode) {
        // decide if the promo is instant or not
        $sql = new SQL();

        $sql->select[] = "A.SubCat";
        $sql->from[] = "AccessoryStock A";
        $sql->where[] = "A.StockCode = '$stockcode'";

        // send to string
        $sql = $sql->ToString($sql);

        // run query
        $result = DB::fetch(DB::query($sql));

        if ($result['SubCat'] == "NEXXUS WEB GIFTS") {
            $instant = "Y";
        } else {
            $instant = "N";
        }

        return $instant;
    }

    private function Insurance($id) {
        // get insurance detail
        switch ($id) {
            case "Y": {
                    $policy = array('id' => '16', 'monthly_cost' => '', 'description' => 'Fonesure Insurance (Free Insurance for 3 months included)', 'image' => '');
                    return $policy;
                }
            case "L": {
                    $policy = array('id' => '55', 'monthly_cost' => '4.99', 'description' => 'AIG Mobile Lite Insurance', 'image' => '');
                    return $policy;
                }
            case "P": {
                    $policy = array('id' => '56', 'monthly_cost' => '7.99', 'description' => 'AIG Mobile Premier Insurance', 'image' => '');
                    return $policy;
                }
        }
    }

    private function Categories($value) {
        // get column equivalent to
        switch ($value) {
            case "CONTRACT": {
                    return "OfferID";
                }
            case "DEALBUILDER": {
                    return "OfferID";
                }
            case "PAYG": {
                    return "OfferID";
                }
            case "PAYGSIMONLY": {
                    return "OfferID";
                }
            case "MOBILEBROADBAND": {
                    return "OfferID";
                }
            case "SIMFREE": {
                    return "HandsetStockCode";
                }
            case "ACCESSORY": {
                    return "AccessoryStockCode";
                }
        }
    }

    private function Descriptions($value) {
        // get column equivalent to
        switch ($value) {
            case "CONTRACT": {
                    return "HandsetDescription";
                }
            case "DEALBUILDER": {
                    return "HandsetDescription";
                }
            case "PAYG": {
                    return "HandsetDescription";
                }
            case "PAYGSIMONLY": {
                    return "HandsetDescription";
                }
            case "MOBILEBROADBAND": {
                    return "HandsetDescription";
                }
            case "SIMFREE": {
                    return "HandsetDescription";
                }
            case "ACCESSORY": {
                    return "AccessoryDescription";
                }
        }
    }

    private function ErrorMessages($value, $description, $limit) {
        // get column equivalent to
        switch ($value) {
            case "1001": {
                    $_SESSION['Checkout'] = false;
                    return "The item you have just selected no longer exists, sorry for any inconvienience caused. (code: 1001)";
                }
            case "1002": {
                    return "You must agree to the terms and conditions of the sale before continuing to the checkout. (code: 1002)";
                }
            case "1003": {
                    return "There has been an error checking out. Please call our Call Centre on 0808 168 0248. (code: 1003)";
                }
            case "2001": {
                    $_SESSION['Checkout'] = false;
                    return "You may only purchase $limit Contract handsets per order. This includes Mobile Broadband items. (code: 2001)";
                }
            case "2002": {
                    $_SESSION['Checkout'] = false;
                    return "You may only purchase $limit Prepay handsets per order. (code: 2002)";
                }
            case "2003": {
                    $_SESSION['Checkout'] = false;
                    return "You may only purchase $limit SIM Free handsets per order. (code: 2003)";
                }
            case "2004": {
                    $_SESSION['Checkout'] = false;
                    return "You may only purchase $limit Accessories per order. This includes associated Accessories. (code: 2004)";
                }
            case "2005": {
                    $_SESSION['Checkout'] = false;
                    return "Sorry, but currently you can only order handsets from a single network at a time. For example, you cannot buy an Orange phone and an O2 phone at the same time. (code: 2005)";
                }
            case "2006": {
                    $_SESSION['Checkout'] = false;
                    return "Sorry, but currently you can only order handsets from a single network at a time. For example, you cannot buy an Orange phone and an O2 phone at the same time. (code: 2006)";
                }
            case "2007": {
                    $_SESSION['Checkout'] = false;
                    return "You may only purchase $limit Prepay SIMs per order. (code: 2007)";
                }
            case "3001": {
                    return "You already had the $description in your basket, so we have simply updated the quantity for you. (code: 3001)";
                }
            case "3002": {
                    $_SESSION['Checkout'] = false;
                    return "Your shopping basket is now empty. (code: 3002)";
                }            
        }
    }

    private function ImageURL($site, $category, $make, $model, $colour, $edition, $network, $width="50", $height="75") {
        // get site url
        $loc = SiteDefaults::URL($site, $_SESSION['Environment']) . "img/cache/";
        $Characters = array("_", " ", "n/a", "/", "+");

        // strtolower all variables
        $make = str_replace($Characters, "", strtolower($make));
        $model = str_replace($Characters, "_", strtolower($model));
        $colour = str_replace($Characters, "", strtolower($colour));
        $edition = str_replace($Characters, "", strtolower($edition));
        $network = strtolower($network);
        if ($colour) {
            $colour = $colour . "_";
        }
        if ($edition) {
            $edition = $edition . "_";
        }
        // return link to landing page
        if ($category == "SIMFREE") {
            $url = $loc . $make . "/" . $model . "/" . $colour . $edition . $width . "_" . $height . ".png";
        } elseif ($category == "ACCESSORY") {
            $url = str_replace("img/cache/", "web3g/img/accessories/", $loc) . strtoupper($model) . ".jpg";
        } else {
            $url = $loc . $make . "/" . $model . "/" . $colour . $edition . $width . "_" . $height . ".png";
        }

        return $url;
    }

    private function UTF8Encode($array) {
        // encode special chars etc for basket array
        $return = array();
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                $return[$k] = Basket::UTF8Encode($v);
            } else {
                $return[$k] = utf8_encode($v);
            }
        }

        return $return;
    }

    public function ClearBasket() {
        $sql = Basket::EmptySQL();
        $query = DB::query($sql);

        Basket::UnsetVars();
    }
}

?>